package loader 
{
	import events.MyEvent;
	
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * ...
	 * @author FireKnight
	 */
	public class TxtLoader extends EventDispatcher 
	{
		protected var myLoader:URLLoader;
		protected var callBack:Function;
		public const IO_ERROR:String="io_error";
		public function TxtLoader(s:String,b:Function,target:IEventDispatcher=null) 
		{
			super(target);
			callBack = b;
			loadFile(s);
			
		}
		
		protected function removeLoader():void
		{
			if (myLoader)
			{
				myLoader = null;
			}
		}//end removeXmlLoader

		
		protected function loadFile(s:String):void
		{
			removeLoader();
			myLoader = new URLLoader();
			myLoader.dataFormat = "text";
			myLoader.load(new URLRequest(s));
			myLoader.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
			myLoader.addEventListener(IOErrorEvent.IO_ERROR, handleIoError, false, 0, true);
		}
		
		protected function handleIoError(e:IOErrorEvent):void
		{
			myLoader.removeEventListener(Event.COMPLETE, onComplete);
			myLoader.removeEventListener(IOErrorEvent.IO_ERROR, handleIoError);
			this.dispatchEvent(new MyEvent(IO_ERROR));
			return;
		}//end handleIoError
		
		protected function onComplete(e:Event):void
		{
			this.callBack(e.target.data);
			myLoader.removeEventListener(Event.COMPLETE, onComplete);
			myLoader.removeEventListener(IOErrorEvent.IO_ERROR, handleIoError);
			
		}
		
	}

}